You can put the script into a separate file, then use $.getScript to load and run it.

Example:

$.getScript("test.js", function(){
    alert("Running test.js");
});

javascript - How to dynamically insert a <script> tag via jQuery after ...

https://stackoverflow.com/questions/3857874/how-to-dynamically-insert-a-script-tag-via-jquery-after-page-load

Can someone please let me know how you would go about dynamically adding a <script> tag into the browser after page load, ideally via jQuery? javascript ...

JQuery to load Javascript file dynamically - Stack Overflow

https://stackoverflow.com/questions/912711/jquery-to-load-javascript-file-dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads. You might want to check if TinyMCE is defined, though, ...

Dynamically adding jQuery to a site for debugging with DOM ...

https://medium.com/backticks-tildes/dynamically-adding-jquery-to-a-site-for-debugging-with-dom-manipulations-ad0786cd49bd

We can still do what we want with vanilla javascript. But if you are like me and using vanilla JS for DOM manipulations tires quickly, you could just decide it ...

How to dynamically load a JS file in JavaScript

https://www.educative.io/answers/how-to-dynamically-load-a-js-file-in-javascript

Dynamic loading · Create a script element. · Set the src , async , and type attributes. · Append the script element to the body. · Check if the file loaded or not ...

Dynamic option creation | Select2 - The jQuery replacement for ...

https://select2.org/tagging

js-example-tags").select2({ tags: true });. Note that when tagging is enabled the user can select from the pre-existing options or create ...